
const mysql = require('mysql');
const connection = mysql.createConnection({
    host: '119.29.90.93',
    user: 'root',
    password: '8666456',
    database: 'todolistdb',
    port: '3306'
});
connection.connect();
function addItem(data) {
    //userlist userid  ???
    var addSql = 'INSERT INTO todolist(id,title,completed) VALUES(?,?,?)';
    var addSqlParams = [data.id, data.title, data.completed];
    //增
    connection.query(addSql, addSqlParams)



    //更新缓存，

    //     ,function (err, result) {
    // connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
    //   if (error) throw error;
    //   console.log('The solution is: ', results[0].solution);
    // });

    // connection.end()

}

function updateItem(data) {
    //??  update where id=data.id
}


async function deleteItem(delid) {
    //??  update where id=data.id
    var delSql = 'delete from todolist where id=?';
    var delSqlParams = [delid];
    //增
    connection.query(delSql, delSqlParams)
    return 'del ok!!!'
}

async function getTodoList() {

    // 先去缓存里查找，有的话，直接从缓存读取，没有的话，从数据库读取，再存到缓存以便下次请求时使用
    const sql = "select * from todolist"

    const mypromise = new Promise((resolve, reject) => {

        connection.query(sql, function (err, result) {
            if (err) {
                reject(err)
                return;
            }

            resolve(result)
        })

    })

    const result = await mypromise
    const myarray = JSON.parse(JSON.stringify(result))   //RowDataPacket
    return myarray

    //存到缓存，后面从缓存里面获取
}

/*
async function addItem(data){

    const tlist=await getTodoList()

    tlist.push(data)

    const jstr=JSON.stringify(tlist)
    const key="todolist"
    client.set(key,jstr)
}*/


module.exports = {
    getTodoList, addItem, deleteItem
}